//
//  BootSpreadImageCenterView.m
//  boot
//
//  Created by Demi on 07/03/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "BootSpreadImageCenterView.h"


#import <Masonry/Masonry.h>
#import <ReactiveObjC/ReactiveObjC.h>

static NSInteger const fps = 30;

static NSTimeInterval const duration = 0.7f;

@interface BootSpreadImageCenterView ()

@property (nonatomic, strong) UIImage *image;
@property (nonatomic, weak) UIImageView *imageView;

@property (nonatomic, strong) NSMutableArray *images;

@end

@implementation BootSpreadImageCenterView

- (instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        _image = image;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        _imageView = imageView;
        [self addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *maker){
            maker.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = image;
    }
    return self;
}

- (CGFloat)radius
{
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    CGFloat diameter = ceil(sqrt(width * width + height * height));
    return ceil(diameter / 2);
}

- (void)animateWithCompletion:(void (^)(void))completion
{
    NSInteger count = ceil(duration * fps);
    CGFloat step = floor([self radius] / (double)count);
    self.images = [self createImagesWithStep:step maxRadius:[self radius]];
    
    dispatch_block_t animating = ^{
        NSMutableArray *images = [self.images mutableCopy];
        @weakify(self);
        RACDisposable *disposable = [[[RACSignal interval:(1.f / (float)fps) onScheduler:[RACScheduler mainThreadScheduler]] takeUntilBlock:^(NSDate *date){
            @strongify(self);
            if (!self)
            {
                return YES;
            }
            if (images.count == 0)
            {
                completion();
                return YES;
            }
            return NO;
        }] subscribeNext:^(NSDate *date){
            self.imageView.image = images.firstObject;
            [images removeObjectAtIndex:0];
        }];
        [self.rac_deallocDisposable addDisposable:disposable];
    };
    animating();
}

- (NSMutableArray<UIImage *> *)createImagesWithStep:(CGFloat)step maxRadius:(CGFloat)maxRadius
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [_image drawInRect:self.bounds];
    
    CGContextSetFillColorWithColor(ctx, [UIColor clearColor].CGColor);
    CGContextSetBlendMode(ctx, kCGBlendModeClear);
    
    NSMutableArray *images = [NSMutableArray array];
    CGFloat radius = step;
    while (radius <= maxRadius)
    {
        CGContextAddArc(ctx, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds), radius, 0.f, 2 * M_PI, 0);
        CGContextDrawPath(ctx, kCGPathFill);
        
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        [images addObject:image];
        radius += step;
    }
    
    UIGraphicsEndImageContext();
    return images;
}

@end
